<template>
    <div class="time-cd">
        {{text}}
    </div>
</template>

<script>
export default {
    props: {
        time: {
            type: [String, Number],
            default: '',
        },
    },
    data() {
        return {
            text: '',

            interval: null,

            oneHour: 60 * 60 * 1000,
            oneMin: 60 * 1000,
            oneSec: 1000,
        };
    },
    methods: {
        setText() {
            var endtime = this.time || '';

            if (typeof endtime === 'string') {
                endtime = endtime.replace(/-/g, '/');
            }

            if (endtime) {
                var endTime = new Date(endtime),
                    currentTime = new Date().getTime() + this.$store.state.server.delta,
                    delta = endTime - currentTime;

                if (delta >= 0) {
                    var remain = this.secToText(delta);

                    this.text = `倒计时：${remain}`;

                    return;
                } else {
                    this.text = '已过期';

                    clearInterval(this.interval);

                    this.$emit('out');

                    return;
                }
            }

            this.text = '';
            return;
        },
        secToText(sec) {
            var hour = Math.floor( sec / this.oneHour ),
                min = Math.floor( sec % this.oneHour / this.oneMin ),
                s = Math.floor( sec % this.oneHour % this.oneMin / this.oneSec );

            return `${hour}:${min}:${s}`;
        },
    },
    mounted() {
        this.setText();

        this.interval = setInterval(() => {
            this.setText();
        }, 1000);
    },
    beforeDestroy() {
        clearInterval(this.interval);
    },
};
</script>

<style lang="scss" scoped>
    .time-cd {
        color: #666666;
    }
</style>